package com.woniu51.order.rabbitmq;

import com.woniu.cinema.api.CinemaFeignClient;
import com.woniu51.order.config.RabbitMqConfig;
import com.woniu51.order.domain.Order;
import com.woniu51.order.domain.OrderSeat;
import com.woniu51.order.mapper.OrderMapper;
import com.woniu51.order.mapper.OrderSeatMapper;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 杨光
 * @date 2022年04月08日 17:46
 */
@Component
public class MessageListener {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderSeatMapper orderSeatMapper;

    @Autowired
    private CinemaFeignClient cinemaFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;


    @RabbitListener(queues = RabbitMqConfig.DLX_QUEUE)
    @Transactional
    public void receiveOrderId(Long orderId){

        //1.更新tb_order
        Order order = new Order();
        order.setOrderId(orderId);
        Integer result = orderMapper.invalidOrder(orderId);
        //检查是否result==1 如果等于1 说明更新成功，否则，说明已经付款
        if(result!=1){
            return;
        }
        //查询订单信息
        Order orderInDb = orderMapper.selectByPrimaryKey(orderId);


        //根据order id 查询tb_order_seat 中的列表
        OrderSeat orderSeat = new OrderSeat();
        orderSeat.setOrderId(orderId);
        List<Integer> seatIdList = orderSeatMapper.select(orderSeat)
                .stream().map(s -> s.getSeatId()).collect(Collectors.toList());

        //调用cinema service接口把座位状态还原
        cinemaFeignClient.revertBatchUpdateSeatStatus(seatIdList);

        //把redis中预减的库存数量加回去
        redisTemplate.opsForValue()
                .increment("redis_key_cache_seat_count_"+orderInDb.getHallMovieId(),seatIdList.size());
    }
}
